//
//  WBMainViewController.swift
//  weibo
//
//  Created by iobit on 2017/05/18.
//  Copyright © 2017 zhuxu. All rights reserved.
//

import UIKit
import SVProgressHUD

class WBMainViewController: UITabBarController {

    
    // 定时器
    var timer:Timer?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupChildControllers()
        setupComposeButton()
        setupTimer()
        setupNewFeatureViews()
        // 设置代理
        delegate = self
        
        // 注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(userLogin(n:)), name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
    }

    
    deinit {
        // 销毁时钟
        timer?.invalidate()
        // 注销通知
        NotificationCenter.default.removeObserver(self)
    }
    
    /*
        portrait    ：竖屏，肖像
        landscape   ：横屏，风景画
        设置支持的方向后，当前的控制器及自控制器都会遵守这个方向
        如果播放视频，通常通过modal展现
     
    */
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
    
    /// 中间撰写加号按钮
    lazy var composeButton:UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")    //lazy避免解包

    // 点击中间撰写加号按钮的监听方法
    func composeStatus() {
        print("撰写微博")
        let vc = UIViewController()
        vc.view.backgroundColor = UIColor.yellow
        let nav = UINavigationController(rootViewController: vc)
        present(nav, animated: true, completion: nil)
        
    }
    
    
    //MARK: 用户登录监听
    @objc private func userLogin(n: Notification) {
        print("用户登录监听\(n)")
        var deadline = DispatchTime.now()
        
        if n.object != nil {
            // 设置指示器渐变样式
            SVProgressHUD.setDefaultMaskType(.gradient)
            SVProgressHUD.showInfo(withStatus: "登录过期，需要重新登录")
            // 修改延迟时间
            deadline = DispatchTime.now() + 2
        }
        DispatchQueue.main.asyncAfter(deadline: deadline) { 
            // 展示登录控制器--通常会和UINavigationController连用，方便返回
            let nav = UINavigationController(rootViewController: WBOAuthViewController())
            self.present(nav, animated: true, completion: nil)
        }

    }
    
}



// MARK: - 新特性视图处理
extension WBMainViewController {
    
    // 设置新特性视图
    func setupNewFeatureViews() {
        let v = isNewVersion ? WBNewFeatureView.newFeatureView() : WBWelcomeView.welcomeView()
        
        view.addSubview(v)
    }
    
    private var isNewVersion: Bool {
        

        // 获取当前版本号
        let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
        
        // 获取沙盒中的版本号
        let path:String = (currentVersion as NSString).cz_appendDocumentDir()
        let sadBoxVersion = (try? String(contentsOfFile: path)) ?? ""
        
        // 当前版本号保存在Documents目录下
        try? currentVersion.write(toFile: path, atomically: true, encoding: .utf8)
        
        // 不相等则显示新特性
        return currentVersion != sadBoxVersion
//        return currentVersion == sadBoxVersion
    }
    

}

// MARK: - UITabBarControllerDelegate
extension WBMainViewController: UITabBarControllerDelegate {
    
    
    /// 将要选择tabBarItem
    ///
    /// - Parameters:
    ///   - tabBarController: tabBarController
    ///   - viewController: 目标控制器
    /// - Returns: 是否切换到目标控制器
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        
        // 获取将要切换到的控制器在数组中的索引
        let index = childViewControllers.index(of: viewController)
        
        // 判断是否是重复点击首页按钮
        if selectedIndex == 0 && index == selectedIndex {
            print("点击首页")
            
            // 让表格滚动到顶部
            let nav = childViewControllers[0] as! UINavigationController
            let vc = nav.childViewControllers[0] as! WBHomeViewController

            vc.tableView?.setContentOffset(CGPoint(x: 0, y: -64), animated: true)
            //延迟一秒加载数据，让表格先到顶部
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: { 
                vc.loadData()
            })
            
            // 清除tableBar的badgeValue
            vc.tabBarItem.badgeValue = nil
            UIApplication.shared.applicationIconBadgeNumber = 0
        }
        
        // 判断目标控制器是否是 UIViewController，若是，则不切换到此控制器
        return !viewController.isMember(of: UIViewController.self)
    }
}

// MARK: - 定时器相关函数
extension WBMainViewController {
    
    func setupTimer() {
        timer = Timer.scheduledTimer(timeInterval: 60.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
    }
    
    func updateTimer() {
        // 未登录，不刷新数据
        if !WBNetWorkManager.shared.userLogon {
            return
        }
        
        WBNetWorkManager.shared.unreadCount { (count) in
            print("刷新到了\(count)条数据")
            // 设置首页
            self.tabBar.items?[0].badgeValue = count > 0 ? "\(count)" : nil
            // 设置APP显示
            UIApplication.shared.applicationIconBadgeNumber = count
        }
    }

}

//extension 类似于OC的分类，在swift中可以用来切分代码块
//可以把相近功能的函数，放在一个extension中，便于代码维护
//注意：extension中不能定义属性
// MARK: - 设置界面
extension WBMainViewController {
    
    //设置撰写加号按钮
    func setupComposeButton() {
        tabBar.addSubview(composeButton)
        let count = CGFloat(childViewControllers.count)
        //将向内缩进的宽度减少
        let width = tabBar.bounds.width/count
        composeButton.frame = tabBar.bounds.insetBy(dx: 2*width, dy: 0)//正数向内缩进，负数向外扩展
        composeButton.addTarget(self, action: #selector(composeStatus), for: .touchUpInside)
    }
    
    
    /// 设置所有子控制器
    func setupChildControllers() {
        
        //获取沙盒中json路径
        let jsonPath = NSHomeDirectory() + "/Documents/main.json"
        var data = NSData(contentsOfFile: jsonPath)
        //判断data是否有内容，如无说明本地沙盒中没有文件
        if data == nil {
            let path = Bundle.main.path(forResource: "main.json", ofType: nil)
            data = NSData(contentsOfFile: path!)
        }
                
        //从bundle加载配置的 json
        //data一定会有内容
        guard let array = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [Dictionary<String, Any>]
            else {
            return
        }
        
        
/*
         输出不了文件。。。。。。。。
        //测试数据格式是否正确
        (array as NSArray).write(toFile: "/Users/iobit/Desktop/demo.plist", atomically: true)
        //数组array导出为json，序列化
        let data = try! JSONSerialization.data(withJSONObject: array, options: [.prettyPrinted])
        (data as NSData).write(toFile: "/Users/iobit/Desktop/main.json", atomically: true)
*/
        
        
        var arrayM = [UIViewController]()
        for dictTmp in array! {
            arrayM.append(controller(dict: dictTmp))
        }
        viewControllers = arrayM
    }
    
    /// 使用字典创建一个子控制器
    ///
    /// - Parameter dit: 信息字典[clsName, title, imageName, visitorInfo]
    /// - Returns: 子控制器
    func controller(dict: [String:Any]) -> UIViewController {
        guard let clsName = dict["clsName"] as? String,
            let title = dict["title"] as? String,
            let imageName = dict["imageName"] as? String,
            let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? WBBaseViewController.Type,
            let visitorInfo = dict["visitorInfo"] as? [String:String]
            else {
                return UIViewController()
        }
        let vc = cls.init()
        vc.title = title
        vc.visitorInfoDictionary = visitorInfo
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)//渲染模式
        //实例化导航控制器时，会调用push方法将rootVC压栈
        let nav = WBNavigationController(rootViewController: vc)
        return nav
    }
        
}
